package com.mariusz.panels;

import java.awt.GridBagLayout;
import org.jdesktop.swingx.JXLabel;
import org.jdesktop.swingx.JXTitledPanel;
import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import org.jdesktop.swingx.JXTextField;
import org.jdesktop.swingx.JXDatePicker;
import org.jdesktop.swingx.JXComboBox;
import javax.swing.DefaultComboBoxModel;

import com.mariusz.data.dto.Property;
import com.mariusz.data.dto.Rentier;
import com.mariusz.data.dto.Room;
import com.mariusz.data.enums.PaymentsIntervals;
import com.mariusz.data.enums.TimeUnits;
import com.mariusz.managers.DataManager;
import com.mariusz.managers.NavigationManager;
import com.mariusz.managers.ReportManager;
import com.mariusz.managers.NavigationManager.Screen;
import com.mariusz.ui.models.PropertiesListModel;
import com.mariusz.ui.models.RoomListModel;
import com.mariusz.utils.Formats;
import com.mariusz.utils.PaymentsCalculator;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;

import org.jdesktop.swingx.JXTitledSeparator;

import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;

import java.awt.Font;
import javax.swing.border.BevelBorder;
import java.text.Format;


public class RentierDetailsPanel extends JXTitledPanel implements ActionListener, PropertyChangeListener{
	private JXTextField rentierFullName ;
	private JXTextField rentierIdentification ;
	private JXTextField retierPhone;
	private JFormattedTextField ftxtDepositAmount;
	private JFormattedTextField ftxtPaymentAmount;
	private JXDatePicker dtpBeginContractDate;
	private JXDatePicker dtpEndContractDate;
	private JXComboBox cmbPaymentIntervals;
	private JTable paymentsTabel;
	private JButton btnCalculatePayments ;
	private JXLabel lblErrorText;
	private JXComboBox cmbRooms ;
	private JXComboBox cmbProperties;
	private JButton btnSave ;
	private JButton btnBack ; 
	private JXComboBox cmbUnits; 
	private JTextField ftxtTermCount;
	public RentierDetailsPanel() {
		getContentContainer().setBackground(Color.WHITE);
		setTitleForeground(new Color(0, 0, 0));
		setTitle("Tenant contract details");
		getContentContainer().setLayout(null);
		
		JXLabel lblRentierFullName = new JXLabel();
		
		lblRentierFullName.setBounds(10, 11, 107, 14);
		lblRentierFullName.setText("Tenant full name:");
		getContentContainer().add(lblRentierFullName);
		
		rentierFullName = new JXTextField();
		rentierFullName.setBounds(110, 6, 285, 21);
		getContentContainer().add(rentierFullName);
		
		JXLabel lblRentierIdentification = new JXLabel();
		lblRentierIdentification.setText("Tenant Identification:");
		lblRentierIdentification.setBounds(288, 33, 127, 14);
		getContentContainer().add(lblRentierIdentification);
		
		rentierIdentification = new JXTextField();
		rentierIdentification.setBounds(425, 28, 190, 21);
		getContentContainer().add(rentierIdentification);
		
		JXLabel lblDepositAmount = new JXLabel();
		lblDepositAmount.setText("Deposit amount:");
		lblDepositAmount.setBounds(228, 94, 107, 14);
		getContentContainer().add(lblDepositAmount);
		
		JXLabel lblContractBeginDate = new JXLabel();
		lblContractBeginDate.setText("Begin date:");
		lblContractBeginDate.setBounds(10, 92, 107, 18);
		getContentContainer().add(lblContractBeginDate);
		
		dtpBeginContractDate = new JXDatePicker();
		dtpBeginContractDate.setBounds(77, 90, 139, 21);
		dtpBeginContractDate.setFormats(SimpleDateFormat.getDateInstance());
		getContentContainer().add(dtpBeginContractDate);
		
		JXLabel lblContractEndDate = new JXLabel();
		lblContractEndDate.setText("Contract term:");
		lblContractEndDate.setBounds(10, 122, 86, 14);
		getContentContainer().add(lblContractEndDate);
		
		dtpEndContractDate = new JXDatePicker();
		dtpEndContractDate.setBounds(110, 144, 154, 21);
		dtpEndContractDate.setFormats(SimpleDateFormat.getDateInstance());
		getContentContainer().add(dtpEndContractDate);
		
		JXLabel lblPaymentAmount = new JXLabel();
		lblPaymentAmount.setText("Weekly payment amount:");
		lblPaymentAmount.setBounds(401, 93, 146, 17);
		getContentContainer().add(lblPaymentAmount);
		
		ftxtPaymentAmount = new JFormattedTextField(Formats.CASH);
		ftxtPaymentAmount.addPropertyChangeListener("value",this);
		ftxtPaymentAmount.setForeground(Color.DARK_GRAY);
		ftxtPaymentAmount.setBounds(547, 94, 78, 21);
		getContentContainer().add(ftxtPaymentAmount);
		
		JXLabel lblPaymentIntervals = new JXLabel();
		lblPaymentIntervals.setText("Payment intervals:");
		lblPaymentIntervals.setBounds(275, 121, 107, 17);
		getContentContainer().add(lblPaymentIntervals);
		
		cmbPaymentIntervals = new JXComboBox();
		cmbPaymentIntervals.setModel(new DefaultComboBoxModel(PaymentsIntervals.values()));
		cmbPaymentIntervals.setBounds(383, 117, 107, 24);
		getContentContainer().add(cmbPaymentIntervals);
		
		JXLabel lblRentierPhone = new JXLabel();
		lblRentierPhone.setText("Tenant phone:");
		lblRentierPhone.setBounds(10, 32, 104, 17);
		getContentContainer().add(lblRentierPhone);
		
		retierPhone = new JXTextField();
		retierPhone.setBounds(110, 29, 172, 21);
		getContentContainer().add(retierPhone);
		
		JXTitledSeparator titledSeparator = new JXTitledSeparator();
		titledSeparator.setTitle("Contract details");
		titledSeparator.setBounds(10, 59, 693, 30);
		getContentContainer().add(titledSeparator);
		
		ftxtDepositAmount = new JFormattedTextField(Formats.CASH);
		ftxtDepositAmount.setForeground(Color.DARK_GRAY);
		ftxtDepositAmount.setToolTipText("The sum of total deposit that rentier should pay in \u00A3");
		ftxtDepositAmount.setBounds(321, 92, 78, 21);
		ftxtDepositAmount.addPropertyChangeListener("value",this);
		getContentContainer().add(ftxtDepositAmount);
		
		JXTitledSeparator titledSeparator_1 = new JXTitledSeparator();
		GridBagLayout gridBagLayout = (GridBagLayout) titledSeparator_1.getLayout();
		gridBagLayout.rowWeights = new double[]{0.0};
		gridBagLayout.rowHeights = new int[]{0};
		gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0};
		gridBagLayout.columnWidths = new int[]{0, 0, 0};
		titledSeparator_1.setTitle("Paymet Details");
		titledSeparator_1.setBounds(10, 210, 693, 30);
		getContentContainer().add(titledSeparator_1);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(20, 238, 652, 153);
		getContentContainer().add(scrollPane);
		
		paymentsTabel = new JTable();
		paymentsTabel.setBorder(null);
		paymentsTabel.setRowSelectionAllowed(false);
		scrollPane.setViewportView(paymentsTabel);
		
		
		btnCalculatePayments = new JButton("Calculate Payments");
		btnCalculatePayments.setBounds(501, 120, 139, 23);
		getContentContainer().add(btnCalculatePayments);
		btnCalculatePayments.addActionListener(this);
		
		lblErrorText = new JXLabel("");
		lblErrorText.setFont(new Font("SansSerif", Font.BOLD, 12));
		lblErrorText.setForeground(Color.RED);
		lblErrorText.setBounds(341, 161, 274, 16);
		getContentContainer().add(lblErrorText);
		
		cmbProperties = new JXComboBox();
		cmbProperties.setBounds(10, 186, 139, 24);
		cmbProperties.addActionListener(this);
		cmbProperties.setModel(new PropertiesListModel(DataManager.getInstance().getProperties()));
		getContentContainer().add(cmbProperties);
		
		cmbRooms = new JXComboBox();
		cmbRooms.setBounds(161, 186, 139, 24);
		getContentContainer().add(cmbRooms);
		
		btnSave = new JButton("Save");
		btnSave.addActionListener(this);
		btnSave.setBounds(348, 392, 100, 40);
		getContentContainer().add(btnSave);
		
		btnBack  = new JButton("Back");
		btnBack.addActionListener(this);
		btnBack.setBounds(238, 392, 100, 40);
		getContentContainer().add(btnBack);
		
		JXLabel lblProperty = new JXLabel("");
		lblProperty.setText("Property:");
		lblProperty.setForeground(Color.BLACK);
		lblProperty.setFont(new Font("SansSerif", Font.PLAIN, 12));
		lblProperty.setBounds(10, 171, 121, 16);
		getContentContainer().add(lblProperty);
		
		JXLabel lblRoom = new JXLabel("");
		lblRoom.setText("Room:");
		lblRoom.setForeground(Color.BLACK);
		lblRoom.setFont(new Font("SansSerif", Font.PLAIN, 12));
		lblRoom.setBounds(161, 171, 121, 16);
		getContentContainer().add(lblRoom);
		
		cmbUnits = new JXComboBox();
		cmbUnits.setModel(new DefaultComboBoxModel(TimeUnits.values()));
		cmbUnits.setSelectedIndex(2);
		cmbUnits.setBounds(157, 117, 107, 24);
		getContentContainer().add(cmbUnits);
		
		ftxtTermCount = new JFormattedTextField((Format)null);
		ftxtTermCount.setToolTipText("");
		ftxtTermCount.setForeground(Color.DARK_GRAY);
		ftxtTermCount.setBounds(110, 116, 45, 24);
		
		ftxtTermCount.addPropertyChangeListener("value",this);
		getContentContainer().add(ftxtTermCount);
		
		JXLabel lblOr = new JXLabel();
		lblOr.setText("or date:");
		lblOr.setBounds(48, 146, 54, 18);
		getContentContainer().add(lblOr);
	
	}

	
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == btnCalculatePayments){
			if(validateCalculationFields()){
				Rentier rentier = DataManager.getInstance().getCurrentRentier();
				fillRentierPaymentsSection(rentier);
				fillRentierContactSection(rentier);
				PaymentsCalculator calc = new PaymentsCalculator();
				rentier.setPayments(calc.calculate(rentier));
				setVisible(true);
			}
		}else if(e.getSource() == btnSave){
			if(validateContactFields()){
				Rentier rentier = DataManager.getInstance().getCurrentRentier();
				fillRentierContactSection(rentier);
				fillRentierPaymentsSection(rentier);
				List<Rentier> rentiers = DataManager.getInstance().getRentiers();
				if(!rentiers.contains(rentier)){
					rentiers.add(rentier);
				}
				
				NavigationManager.getInstance().switchTo(Screen.RENTIER_LIST);
			}
			
		}else if(e.getSource() == btnBack){
			NavigationManager.getInstance().switchTo(Screen.RENTIER_LIST);
		}else if(e.getSource() == cmbProperties){
			Property property =(Property) cmbProperties.getSelectedItem();
			if(property != null){
				cmbRooms.setModel(new RoomListModel(property.getRooms()));
				cmbProperties.setSelectedItem(property);
			}
		}
		
	}

	private void fillRentierPaymentsSection(Rentier rentier){
		rentier.setContractBeginDate(dtpBeginContractDate.getDate());
		rentier.setContractEndDate(dtpEndContractDate.getDate());
		rentier.setPaymentAmount(((Number)ftxtPaymentAmount.getValue()).doubleValue());
		rentier.setDepositAmount(((Number)ftxtDepositAmount.getValue()).doubleValue());
		rentier.setPaymentInterval(PaymentsIntervals.values()[cmbPaymentIntervals.getSelectedIndex()]);
	}

	private void fillRentierContactSection(Rentier rentier){
		rentier.setName(rentierFullName.getText());
		rentier.setDocument(rentierIdentification.getText());
		rentier.setTelephone(retierPhone.getText());
		if(cmbProperties.getSelectedItem()!=null){
		rentier.setProperty((Property)cmbProperties.getSelectedItem());
		}
		if(cmbRooms.getSelectedItem() != null){
		rentier.setRoom((Room)cmbRooms.getSelectedItem());
		}
	}
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		//TODO sprawdzic czy combo tez trigeruje.
		if(evt.getSource() == ftxtTermCount){
			try{
				String oVal = ftxtTermCount.getText();

				int value = Integer.valueOf((String)oVal);
				Calendar cal = Calendar.getInstance();
				cal.setTime(dtpBeginContractDate.getDate());
				switch(TimeUnits.values()[cmbUnits.getSelectedIndex()]){
					case DAYS: cal.add(Calendar.DAY_OF_YEAR,value);break;
					case WEEKS: cal.add(Calendar.WEEK_OF_YEAR, value);break;
					case MONTHS: cal.add(Calendar.MONTH,value); break;
				}
				dtpEndContractDate.setDate(cal.getTime());
			
			}catch(NumberFormatException e){
				//do nothing
			}
		}else if(evt.getSource() == ftxtDepositAmount){
			DataManager.getInstance().getCurrentRentier().setDepositAmount(((Number)ftxtDepositAmount.getValue()).doubleValue());
		}else if (evt.getSource() == ftxtPaymentAmount){
			DataManager.getInstance().getCurrentRentier().setPaymentAmount(((Number)ftxtPaymentAmount.getValue()).doubleValue());
			
		}else if(evt.getSource() == cmbProperties){
			Property property =(Property) cmbProperties.getSelectedItem();
			if(property != null){
				cmbRooms.setModel(new RoomListModel(property.getRooms()));
			}
		}
		
	}
	@Override
	public void setVisible(boolean arg0) {
		if(arg0){
			Rentier rentier = DataManager.getInstance().getCurrentRentier();
			if(rentier == null){
				NavigationManager.getInstance().switchTo(Screen.RENTIER_LIST);
			}else{
				rentierFullName.setText(rentier.getName());
				retierPhone.setText(rentier.getTelephone());
				rentierIdentification.setText(rentier.getDocument());
				if(rentier.getProperty() != null){
					cmbProperties.getModel().setSelectedItem(rentier.getProperty());
				}
				if(rentier.getRoom() != null){
					cmbRooms.getModel().setSelectedItem(rentier.getRoom());
				}
				
				if(rentier.getContractBeginDate() != null){
					dtpBeginContractDate.setDate(rentier.getContractBeginDate());
				}
				if(rentier.getContractEndDate() != null){
				dtpEndContractDate.setDate(rentier.getContractEndDate());
				}
				if(rentier.getDepositAmount() != null){
					//setting the content.
					ftxtDepositAmount.setValue(rentier.getDepositAmount());
				}
				if(rentier.getPaymentAmount() != null){
					ftxtPaymentAmount.setValue(rentier.getPaymentAmount());
				}
				if(rentier.getPaymentInterval() != null){
					cmbPaymentIntervals.setSelectedItem(rentier.getPaymentInterval());
				}
				
				paymentsTabel.setModel(
						DataManager.getInstance().toPaymentsModel(
								DataManager.getInstance().getCurrentRentier()));
			}
				
		}
		super.setVisible(arg0);
		this.repaint();
	}
	

	private boolean validateCalculationFields() {
		lblErrorText.setText("");
		if(dtpBeginContractDate.getDate()== null){
			lblErrorText.setText("Please enter correct Contract Begin date.");
			return false;
		}else if(dtpEndContractDate.getDate() == null){
			lblErrorText.setText("Please enter correct Contract End date.");
			return false;
		}else if(dtpEndContractDate.getDate().before(dtpBeginContractDate.getDate())){
			lblErrorText.setText("Please ensure that end date is after begin date.");
			return false;
		}
				
		return true;
	}
	private boolean validateContactFields() {
		lblErrorText.setText("");
		if(rentierFullName.getText().isEmpty()){
			lblErrorText.setText("Please enter the rentier Name.");
			return false;
		}else if(retierPhone.getText().isEmpty()){
			lblErrorText.setText("Please enter the rentier Phone.");
			return false;
		}else if(rentierIdentification.getText().isEmpty()){
			lblErrorText.setText("Please enter the rentier ID.");
			return false;
		}
				
		return true;
	}







}
